﻿//*** Guidance generated code ***//
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;

using NHibernate;
using NHibernate.Criterion;

using ProjectBase.Core;
using ProjectBase.Data;
using ProjectBase.Data.NH;

using Survey.Common;
using Survey.Common.Data.Services;
using Survey.Entity;
using Survey.Entity.Services;

namespace Survey.Data.Services
{
    public class UserDao : BaseDao<User, int, UserFilter>, IUserDao
    {
        #region Find
        public override IEnumerable<User> Find(UserFilter filter)
        {
            Criteria.AddCompare(() => filter.IdExact); // Searches for exact ID
            Criteria.AddEqual(() => filter.LoginExact); // Searches for exact match

            // user
            UserDao.AppendCriteria(Criteria, filter);

            return GetListByCriteria(filter);
        }

        public static void AppendCriteria(ICriteria criteria, UserFilter filter, string subCriteriaPath = null)
        {
            if (!filter.IsNotEmpty()) // filter parameters for inner User filter
            {
                return;
            }
            var subCriteria = subCriteriaPath.IsEmpty()
                ? criteria                                     // existing criteria to be filled
                : criteria.CreateSubCriteria(subCriteriaPath); // inner criteria will be created

            subCriteria.AddLike(() => filter.Login);
            subCriteria.AddLike(() => filter.FirstName);
            subCriteria.AddLike(() => filter.LastName);
        }
        #endregion Find

        #region IUserDao Members
        /// <summary>
        ///     Sets the ID to the last + 1
        /// </summary>
        /// <param name = "entity"></param>
        /// <returns></returns>
        public override User Add(User entity)
        {
            var last = GetEntityWithMaxId();

            entity.SetId(last.Is() ? last.ID + 1 : 1);

            entity = base.Add(entity);
            Session.Flush();
            return entity;
        }

        public virtual IEnumerable<User> GetAll()
        {
            var list = Session.CreateCriteria<User>().List<User>();
            return list;
        }
        #endregion

        /// <summary>
        ///     Gets the Last used ID
        /// </summary>
        /// <returns></returns>
        protected virtual User GetEntityWithMaxId()
        {
            return Session
                .CreateCriteria(typeof(User))
                .AddOrder(new Order(Str.Common.ID, false))
                .SetMaxResults(1)
                .UniqueResult<User>();
        }
    }
}